package com.ewo.realm;

import com.ewo.util.ApplicationContextUtill;
import com.ewo.service.EmpService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class CustomRealm extends AuthorizingRealm {
    @Resource
    private ApplicationContextUtill applicationContextUtill;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermission("add");
        authorizationInfo.addStringPermission("delete");
        authorizationInfo.addStringPermission("update");
        authorizationInfo.addStringPermission("select");
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        String credential= new String((char[])authenticationToken.getCredentials());

        //从数据库获取用户名密码认证
        EmpService empService = (EmpService)applicationContextUtill.getBean("empServiceImpl");
        String password = empService.FindPwdByUsername(principal);
        System.out.println("获取到的pwd:"+password);
        if (principal.isEmpty()){
            throw new AccountException("用户名错误");
        }else if(!credential.equals(password)){
            throw new AccountException("密码错误");
        }
        return new SimpleAuthenticationInfo(principal, credential,getName());
    }
}
